<?php
/**
 * 学校模型
 */

namespace app\common\model;

use think\model\concern\SoftDelete;

class School extends CommonBaseModel {
	use SoftDelete;
	// 自定义选择数据
	public const TAG_TEXT = [0 => '小学', 1 => '初中'];
	protected $name = 'school';
	protected $autoWriteTimestamp = true;

	// 可搜索字段
	public array $searchField = ['name', 'username'];

	// 可作为条件的字段
	public array $whereField = [];

	// 可作为多选条件的字段
	public array $multiWhereField = [];

	// 可做为时间
	public array $timeField = [];

	/**
	 * 状态获取器
	 */
	public function getStatusTextAttr($value, $data): string {
		return self::BOOLEAN_TEXT[$data['status']];
	}

	public static function onBeforeInsert($data): void {
		$data->password = (new self)->setEncryptPassword($data->password);
	}

	/**
	 * 更新前监测密码是否变更
	 * @param User $data
	 * @return void
	 */
	public static function onBeforeUpdate($data): void {
		$old = (new self())->where('id', '=', $data->id)->findOrEmpty();
		/**@var User $old */
		if ($data->password !== $old->password) {
			$data->password = (new self)->setEncryptPassword($data->password);
		}
	}
	protected function setEncryptPassword($password): string {
		return base64_encode(password_hash($password, 1));
	}
	public function getTagTextAttr($value, $data): string {
		return self::TAG_TEXT[$data['tag']];
	}
}
